import { parentPort } from "worker_threads";
import { KlMcClient } from "./KlMcClient";

let client: KlMcClient | null = null;

// 初始化客户端（仅一次）
async function initializeClient(ipAddr: string, port: number, options: any) {
  try {
    client = new KlMcClient(ipAddr, port, options);
    await client.open();
    parentPort?.postMessage({ type: "init_success" });
  } catch (error: any) {
    parentPort?.postMessage({ type: "init_error", error: error.message });
  }
}

async function close() {
  try {
    client?.close();
    parentPort?.postMessage({ type: "close_success" });
  } catch (error: any) {
    parentPort?.postMessage({ type: "close", error: error.message });
  }
}

// 处理写操作
async function handleWrite(deviceName: string, str: string): Promise<boolean> {
  if (!client) throw new Error("Client not initialized");
  return await client.writeString(deviceName, str);
}

// 处理读操作
async function handleRead(
  deviceName: string,
  strLength: number
): Promise<string> {
  if (!client) throw new Error("Client not initialized");
  return await client.readString(deviceName, strLength);
}

// 处理写数组
async function handleWriteArr(
  deviceName: string,
  arr: number[]
): Promise<boolean> {
  if (!client) throw new Error("Client not initialized");
  return await client.setWords(deviceName, arr);
}

// 处理读数组
async function handleReadArr(
  deviceName: string,
  length: number
): Promise<string> {
  if (!client) throw new Error("Client not initialized");
  return await client.getWords(deviceName, length);
}

// 处理写数字
async function handleWriteNum(
  deviceName: string,
  num: number
): Promise<boolean> {
  if (!client) throw new Error("Client not initialized");
  return await client.setWord(deviceName, num);
}

// 处理读数字
async function handleReadNum(deviceName: string): Promise<number> {
  if (!client) throw new Error("Client not initialized");
  return await client.getWord(deviceName);
}

// 消息监听器
parentPort?.on("message", async (msg: any) => {
  try {
    switch (msg.type) {
      case "init":
        await initializeClient(msg.ipAddr, msg.port, msg.options);
        break;

      case "close":
        await close();
        break;
      case "write_str":
        const writeResult = await handleWrite(msg.deviceName, msg.str);
        parentPort?.postMessage({ type: "write_result", success: writeResult });
        break;
      case "read_str":
        const readResult = await handleRead(msg.deviceName, msg.strLength);
        parentPort?.postMessage({ type: "read_result", data: readResult });
        break;
      case "write_arr":
        const writeArrResult = await handleWriteArr(msg.deviceName, msg.arr);
        parentPort?.postMessage({
          type: "write_result",
          success: writeArrResult,
        });
        break;
      case "read_arr":
        const readArrResult = await handleReadArr(
          msg.deviceName,
          msg.arrLength
        );
        parentPort?.postMessage({ type: "read_result", data: readArrResult });
        break;
      case "write_num":
        const writeNumResult = await handleWriteNum(msg.deviceName, msg.num);
        parentPort?.postMessage({
          type: "write_result",
          success: writeNumResult,
        });
        break;
      case "read_num":
        const readNumResult = await handleReadNum(msg.deviceName);
        parentPort?.postMessage({ type: "read_result", data: readNumResult });
        break;
      default:
        throw new Error(`Unknown message type: ${msg.type}`);
    }
  } catch (error: any) {
    parentPort?.postMessage({ type: "error", error: error.message });
  }
});
